﻿/**
 * SlotDuino
 * 
 * Copyright (c) 2011/2012 Thiago Hummel Moreira, Ricardo Mizuuti, Rafael Mufato, Bruno Sakai, Andre Turina
 * 
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
 * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
 * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
using System;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using SlotDuino.DAL;
using SlotDuino.Util;
using System.Collections.Generic;
using System.Data;
using System.Collections.ObjectModel;

namespace SlotDuino.UI.Controls
{
    /// <summary>
    /// Interaction logic for RaceCreate.xaml
    /// </summary>
    public partial class RaceCreate : UserControl
    {
        #region Dependency properties
        public static readonly DependencyProperty TrackProperty = DependencyProperty.Register("Track", typeof(Track), typeof(RaceCreate));
        public static readonly DependencyProperty RaceProperty = DependencyProperty.Register("Race", typeof(FreeRace), typeof(RaceCreate));
        #endregion

        #region Private attributes
        ObservableCollection<Slot> _slotList;
        #endregion

        #region Public properties
        public Track Track
        {
            get { return (Track)GetValue(TrackProperty); }
            set { SetValue(TrackProperty, value); }
        }

        public List<Pilot> Pilots { get; set; }

        public FreeRace Race
        {
            get { return (FreeRace)GetValue(RaceProperty); }
            set { SetValue(RaceProperty, value); }
        }

        public Operator LoggedUser
        {
            get { return Authentication.GetLoggedUser(); }
        }
        #endregion

        #region Public events
        public event EventHandler RaceCreated;
        public event EventHandler Cancel;
        #endregion

        public RaceCreate()
        {
            InitializeComponent();
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            if (null == Track) return;

            //Create the Race object
            Race = new FreeRace();
            Race.Track = Track;
            Race.State = (byte)RaceState.New;
            Race.OperatorId = LoggedUser.Id; //This reference is out of our context

            //Setup view sources
            var slotsViewSource = (CollectionViewSource)FindResource("slotsViewSource");
            ///@TODO: List only avaliable slots
            _slotList = new ObservableCollection<Slot>(Track.Slots);
            slotsViewSource.Source = _slotList;

            var voltagesViewSource = (CollectionViewSource)FindResource("voltagesViewSource");
            voltagesViewSource.Source = Track.Voltages;
            //Select the default voltage
            cmbVoltage.SelectedItem = Track.Voltages.Single(v => v.Default == true);

            var pilotsViewSource = (CollectionViewSource)FindResource("pilotsViewSource");
            pilotsViewSource.Source = Pilots;

            var raceSlotsViewSource = (CollectionViewSource)FindResource("raceSlotsViewSource");
            raceSlotsViewSource.Source = Race.Slots;
        }

        private void btnAddToList_Click(object sender, RoutedEventArgs e)
        {
            //Get the selected slot and remove it from list
            var slot = (Slot)cmbSlot.SelectedItem;
            _slotList.Remove(slot);

            //Create the RaceSlot
            RaceSlot raceSlot = new RaceSlot();
            raceSlot.Slot = slot;
            raceSlot.Pilot = GetPilot();
            raceSlot.Voltage = ((Voltage)cmbVoltage.SelectedItem).Id;
            
            //Add the RaceSlot to the Race
            Race.Slots.Add(raceSlot);
        }

        private void btnCreateRace_Click(object sender, RoutedEventArgs e)
        {
            //Set race duration
            Race.Duration = TextToTime(int.Parse(txtTime.Text), cmbSegMin.Text);

            //Fire the RaceCreated event
            var handler = RaceCreated;
            if (null != handler)
                handler(this, new EventArgs());
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            //Fire the Cancel event
            var handler = Cancel;
            if (null != handler)
                handler(this, new EventArgs());
        }

        private Pilot GetPilot()
        {
            Pilot pilot = (Pilot)cmbPilots.SelectedItem;
            if (null == pilot)
            {
                pilot = new Pilot();
                pilot.Name = cmbPilots.Text;
                pilot.Nickname = cmbPilots.Text;
            }

            return pilot;
        }

        private TimeSpan TextToTime(int value, string segOrMin) {
            TimeSpan ts = TimeSpan.Zero;
            if (segOrMin == "minutos")
            {
                ts = new TimeSpan(0, value, 0);
            }
            else if (segOrMin == "segundos")
            {
                ts = new TimeSpan(0, 0, value);
            }

            return ts;
        }
    }
}
